#
#  gStorageModel.py
#  gStorageBrowser
#
#  Created by Wang Shao-chuan on 2011/1/1.
#  Copyright (c) 2011 National Taiwan University. All rights reserved.
#

import sys
import os
from Foundation import *
from GoogleStorage import GoogleStorage


class gStorageNode(object):
  _gstorage = None
  
  def __init__(self, bucketName=None, itemName='', column=0):
    self.bucketName = bucketName
    self.itemName = itemName
    self.title = bucketName if column==0 else os.path.basename(itemName)
    self._children = []
    self._itemNames = []
    self._column = column


  @property
  def gstorage(self):
    if gStorageNode._gstorage is None:
      gStorageNode._gstorage = GoogleStorage()
    return gStorageNode._gstorage
    
  def atRow(self, row):
    return self.children[row]
  
  @property
  def children(self):
    if bool(self._children):
      return self._children
    itemNames = self.gstorage.itemNames(self.bucketName)
    paths = ['/'.join(name.split('/')[:self._column+1]) for name in itemNames]
    paths = [p for p in paths if p.strip() and p.startswith(self.itemName)]
    paths = list(set(paths))
    self._children = [gStorageNode(self.bucketName, name, self._column+1) for name in paths]
    return self._children
  
  @property  
  def childrenCount(self):
    return len(self.children)
    
  @property
  def isRoot(self):
    return False
    
  @property
  def isLeaf(self):
    if bool(self.itemName) and bool(self.bucketName):
      return self.gstorage.hasItemInBucket(self.itemName, self.bucketName)
    return False
        
class gStroageRootNode(gStorageNode):
  def __init__(self):
    self._children = []
    
  @property
  def children(self):
    if self._children:
      return self._children
    
    bucketNames = self.gstorage.bucketNames
    self._children = [gStorageNode(name) for name in bucketNames]
    return self._children
    
  @property
  def isRoot(self):
    return True